package cn.zjitc.jdbc.util;


import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {

    // 数据源对象，使用Druid连接池
    private static DataSource dataSource;

    static {
        try {
            // 加载配置文件
            Properties properties = new Properties();
            // 假设配置文件在类路径下，例如：template_druid.properties
            properties.load(DruidUtils.class.getClassLoader().getResourceAsStream("jdbc/druid.properties"));

            // 创建数据源
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new ExceptionInInitializerError("Druid数据源初始化异常：" + e.getMessage());
        }
    }

    /**
     * 获取数据源对象
     */
    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
}
